package com.example.tianling.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.tianling.common.utils.MinioUtils;
import com.example.tianling.entity.RoomEntity;
import com.example.tianling.service.RoomService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RTCController {
    private static final Logger logger = LoggerFactory.getLogger(RTCController.class);

    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private RoomService roomService;

    @PostMapping("/rtc")
    @ResponseBody
    public void getRtcMessage(@RequestBody String params) throws Exception {
        JSONObject paramsJSONObject = JSONObject.parseObject(params);
        Integer eventType = paramsJSONObject.getInteger("eventType");
        logger.info("录制响应码：{}", eventType);
        if (eventType.equals(300)) {
            JSONObject data = (JSONObject) paramsJSONObject.get("data");
            logger.info("房间{}录制完成", data.getString("channelName"));
        } else if (eventType.equals(3)) {
            JSONObject data = (JSONObject) paramsJSONObject.get("data");
            logger.info("录制文件参数: {}", data);
            String url = data.getString("url");
            String roomId = data.getString("channelName");
            RoomEntity room = roomService.getRoom(Integer.parseInt(roomId));

            String recordUrl = minioUtils.uploadRecord(room.getType(), roomId, url);
            room.setRecordUrl(recordUrl);
            roomService.updateById(room);

            logger.info("房间{}录制文件可以下载：{}", data.getString("channelName"), data.getString("url"));
        } else if (eventType.equals(302)) {
            logger.info(params);
        } else if (eventType.equals(303)) {
            logger.info(params);
        } else if (eventType.equals(304)) {
            logger.info(params);
        }else if (eventType.equals(301)) {
            logger.info(params);
        }else if (eventType.equals(305)) {
            logger.info(params);
        }
    }
}
